using System;
using System.IO;
using System.Collections.Generic;
using System.Text;

using LumiSoft.Net.IO;

namespace LumiSoft.Net.MIME
{
    /// <summary>
    /// Repesent MIME single part entity body. 
    /// </summary>
    public class MIME_BinaryBody : MIME_Body
    {
        private Stream m_pStream        = null;
        private Stream m_pStreamEncoded = null;

        /// <summary>
        /// Default constructor.
        /// </summary>
        /// <param name="owner">Owner MIME entity.</param>
        /// <exception cref="ArgumentNullException">Is raised when <b>owner</b> is null.</exception>
        internal MIME_BinaryBody(MIME_Entity owner) : base(owner)
        {
        }

        #region method Dispose

        /// <summary>
        /// Cleans up any resources being used.
        /// </summary>
        public override void Dispose()
        {
            base.Dispose();

            // TODO:
        }

        #endregion


        #region method SetStream

        /// <summary>
        /// 
        /// </summary>
        /// <param name="stream"></param>
        /// <param name="owner"></param>
        public void SetStream(Stream stream,bool owner)
        {
            // TODO:
        }

        #endregion

        #region method SetStreamEncoded

        /// <summary>
        /// Sets encoded data stream.
        /// </summary>
        /// <param name="stream">Encoded data stream.</param>
        /// <param name="owner"></param>
        public void SetStreamEncoded(Stream stream,bool owner)
        {
            if(stream == null){
                throw new ArgumentNullException("stream");
            }

            // TODO:

            m_pStreamEncoded = stream;
            m_pStream        = null;
        }

        #endregion

        #region override method ToStream

        /// <summary>
        /// Stores MIME entity body to the specified stream
        /// </summary>
        /// <param name="stream">Stream where to store body. Storing starts from stream current position.</param>
        /// <exception cref="ArgumentNullException">Is raised when <b>stream</b> is null.</exception>
        public override void ToStream(Stream stream)
        {
            if(stream == null){
                throw new ArgumentNullException("stream");
            }

            Net_Utils.StreamCopy(this.StreamEncoded,stream,32000);
        }

        #endregion


        #region method ParseFromStream

        /// <summary>
        /// Parses MIME entity body from the specified stream.
        /// </summary>
        /// <param name="stream">Stream from where to parse body.</param>
        /// <param name="owner">Specifies if body will be stream owner.</param>
        /// <returns>Returns true if this is last boundary in the message or int multpiart "body parts".</returns>
        internal override bool ParseFromStream(Stream stream,bool owner)
        {   
            byte[] buffer =  new byte[32000];
       
            string boundary = null;
            if(this.Owner.Parent != null && this.Owner.Parent.ContentType != null){
                boundary = this.Owner.Parent.ContentType.Param_Boundary;
            }
                        
            // We are stream owner and stream supports seeking, we can use PartialStream.
            if(owner && stream.CanSeek){
                long start = stream.Position;

                // Entity is child of multipart.
                if(boundary != null){
                    SmartStream reader = new SmartStream(stream,false);
                    // Seek bounday end or next boundary start.
                    while(true){
                        int readedCount = reader.ReadLine(buffer,0,buffer.Length - 2,SizeExceededAction.ThrowException);
                        // We reached end of stream. Normally we need to get boundary end tag here, just consider boundary closed.
                        if(readedCount == 0){
                            SetStreamEncoded(new PartialStream(stream,start,stream.Position - start),true);

                            return true;
                        }
                        // We have possible boundary, check if it is.
                        else if(readedCount >= 2 && buffer[0] == '-' && buffer[1] == '-'){
                            string line = Encoding.Default.GetString(buffer,0,readedCount);
                            // We got boundary end tag and this is last boundary in "body parts".
                            if(line == "--" + boundary + "--"){
                                SetStreamEncoded(new PartialStream(stream,start,stream.Position - start),true);

                                return true;
                            }
                            // We got boundary end tag, there are more boundaries.
                            else if(line == "--" + boundary){
                                SetStreamEncoded(new PartialStream(stream,start,stream.Position - start),true);

                                return false;
                            }
                        }
                    }
                }
                // Root entity, simple single part MIME message.
                else{
                    SetStreamEncoded(new PartialStream(stream,start,stream.Length - stream.Position),true);

                    return true;
                }                
            }
            // We must create copy from body data, stream won't support seeking.
            // This is very common case when MIME message is parsed from NetworkStream directly.
            else{
                FileStream fs = File.Create(Path.GetTempFileName(),32000,FileOptions.DeleteOnClose);

                // Entity is child of multipart.
                if(boundary != null){
                    SmartStream reader = new SmartStream(stream,false);
                    // Seek bounday end or next boundary start.
                    while(true){
                        int readedCount = reader.ReadLine(buffer,0,buffer.Length - 2,SizeExceededAction.ThrowException);
                        // We reached end of stream. Normally we need to get boundary end tag here, just consider boundary closed.
                        if(readedCount == 0){
                            return true;
                        }
                        // We have possible boundary, check if it is.
                        else if(readedCount >= 2 && buffer[0] == '-' && buffer[1] == '-'){
                            string line = Encoding.Default.GetString(buffer,0,readedCount);
                            // We got boundary end tag and this is last boundary in "body parts".
                            if(line == "--" + boundary + "--"){
                                return true;
                            }
                            // We got boundary end tag, there are more boundaries.
                            else if(line == "--" + boundary){
                                return false;
                            }
                        }

                        // If we reach so far, it's entity body line.
                        // Store CRLF to readed buffer (We allocated 2 bytes for it before).
                        buffer[readedCount + 0] = (byte)'\r';
                        buffer[readedCount + 1] = (byte)'\n';
                        // Write body line.
                        fs.Write(buffer,0,readedCount + 2);                        
                    }
                }
                // Root entity, simple single part MIME message.
                else{
                    // Just copy body data to tmp file.
                    Net_Utils.StreamCopy(stream,fs,32000);
                }

                fs.Position = 0;
                SetStreamEncoded(fs,true);

                return true;
            }
        }

        #endregion


        #region Properties Impelementation

        /// <summary>
        /// Gets or sets body data. NOTE: Use this property with care, because body data may be very big and you may run out of memory.
        /// </summary>
        /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception>
        public byte[] Data
        {
            get{
                if(this.IsDisposed){
                    throw new ObjectDisposedException(this.GetType().Name);
                }

                MemoryStream ms = new MemoryStream();
                Net_Utils.StreamCopy(this.Stream,ms,32000);

                return ms.ToArray(); 
            }

            set{
                if(this.IsDisposed){
                    throw new ObjectDisposedException(this.GetType().Name);
                }

                SetStream(new MemoryStream(value),true);
            }
        }

        /// <summary>
        /// Gets body data stream.
        /// </summary>
        /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception>
        public Stream Stream
        {
            get{ 
                if(this.IsDisposed){
                    throw new ObjectDisposedException(this.GetType().Name);
                }

                return m_pStream; 
            }
        }

        /// <summary>
        /// Gets body ecoded data stream.
        /// </summary>
        /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception>
        public Stream StreamEncoded
        {
            get{
                if(this.IsDisposed){
                    throw new ObjectDisposedException(this.GetType().Name);
                }

                return m_pStreamEncoded; 
            }
        }

        #endregion

    }
}
